package com.forum.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.forum.bean.*;
import com.forum.common.Result;
import com.forum.dto.*;
import com.forum.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ArticleService {
    @Autowired
    private ArticlesMapper articlesMapper;

    @Autowired
    private ArticleContentMapper articleContentMapper;

    @Autowired
    private ArticleAuditMapper articleAuditMapper;

    @Autowired
    private ArticleLikeMapper articleLikeMapper;

    @Autowired
    private ArticleViewMapper articleViewMapper;

    // 获取文章列表
    public Result<IPage<ArticleListDto>> getArticleList(int pageNum, int pageSize,String searchTitle, Integer userId,Integer status,Integer typeId) {
        Page<ArticleListDto> page = new Page<>(pageNum, pageSize);
        page.addOrder(OrderItem.desc("createAt"));
        return Result.ok(articlesMapper.selectArticleList(page,searchTitle, userId,status,typeId));
    }

//    推荐文章
    public Result<IPage<ArticleListDto>> getRecommendArticleList(int pageNum, int pageSize,String searchTitle, Integer userId,Integer status) {
        Page<ArticleListDto> page = new Page<>(pageNum, pageSize);
        page.addOrder(OrderItem.desc("like_count"));
        return Result.ok(articlesMapper.selectArticleList(page,searchTitle, userId,status,null));
    }

    // 获取文章详情
    public Result<ArticleDetailDto> getArticleDetail(Integer articleId, Integer userId) {
        try {
            ArticleDetailDto detail = articlesMapper.selectArticleDetail(articleId, userId);
            if(detail == null) {
                return Result.fail("文章不存在");
            }
            List<CommentDto> comments = articlesMapper.selectComments(articleId);
            detail.setComments(comments);

            QueryWrapper<ArticleViews> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("article_id", articleId);
            // 添加阅读记录
            Long count = articleViewMapper.selectCount(queryWrapper);
            if(count == 0) {
                // 文章的阅读量加1
                Articles article = new Articles();
                article.setId(articleId);
                article.setViewCount(detail.getViewCount() + 1);
                articlesMapper.updateById(article);

                // 新增浏览记录
                ArticleViews articleViews = new ArticleViews();
                articleViews.setArticleId(articleId);
                articleViews.setUserId(userId);
                articleViews.setCreatedAt(LocalDateTime.now());
                articleViewMapper.insert(articleViews);
            }

            return Result.ok(detail);
        } catch(Exception e) {
            return Result.fail("查询失败：" + e.getMessage());
        }
    }

    // 写文章
    @Transactional
    public Result<Articles> createArticle(ArticleCreateRequest request) {
        try {
            // 处理文章摘要
            String content = request.getContent();
            String desc;
            if (content.length() <= 100) {
                desc = content;
            } else {
                desc = content.substring(0, 100) + "...";
            }

            // 构建主表 Article 对象
            Articles article = new Articles();
            article.setTitle(request.getTitle());
            article.setDesc(desc);
            article.setIsPaid(0);       // 默认不付费
            article.setStatus(request.getStatus());           // 文章状态设为待审核（1）
            article.setUserId(request.getUserId());
            article.setCreatedAt(LocalDateTime.now());
            article.setLikeCount(0);
            article.setViewCount(0);
            article.setCommentCount(0);
            article.setTypeId(request.getTypeId());
            int row = 0;


            // 如果传入了id 则为修改 那么更新对应记录就行
            if(request.getId() != null) {
                article.setId(request.getId());
                 row = articlesMapper.updateById(article);
                if(row != 1) {
                    return Result.fail("更新文章主表失败");
                }

                // 同步更新article-contents
                ArticleContents articleContent = new ArticleContents();
                articleContent.setArticleId(article.getId());
                articleContent.setContent(content);
                UpdateWrapper<ArticleContents> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("article_id", article.getId());
                row = articleContentMapper.update(articleContent,updateWrapper);

                if(row != 1) {
                    return Result.fail("更新文章内容失败");
                }
            }
            else{
                // 插入文章主表记录（文章 id 会自动生成）
                 row = articlesMapper.insert(article);
                if(row != 1) {
                    return Result.fail("写入文章主表失败");
                }


                // 插入文章内容到 article_contents 表
                ArticleContents articleContent = new ArticleContents();
                articleContent.setArticleId(article.getId());
                articleContent.setContent(content);
                row = articleContentMapper.insert(articleContent);
                if(row != 1) {
                    return Result.fail( "写入文章内容失败");
                }

            }

            // 如果是草稿那么不添加到审核表
            if(request.getStatus() == 1) {
                return Result.ok(article);
            }



            // 插入审核记录到文章审核表（待审核状态）
            ArticleAudits audit = new ArticleAudits();
            audit.setArticleId(article.getId());
            audit.setStatus(1); // 1 表示待审核
            audit.setCreatedAt(LocalDateTime.now());
            row = articleAuditMapper.insert(audit);
            if(row != 1) {
                return Result.fail("写入审核记录失败");
            }

            return Result.ok(article);
        } catch(Exception e) {
            return Result.fail("创建文章异常：" + e.getMessage());
        }
    }


    /**
     * 点赞/取消点赞逻辑：
     * - 如果当前用户对该文章已点赞，则删除点赞记录、文章的点赞数减1
     * - 否则，插入点赞记录、文章的点赞数加1
     */
    @Transactional
    public Result<String> toggleLike(LikeRequest req) {
        try {
            Integer articleId = req.getArticleId();
            Integer userId = req.getUserId();

            // 构造查询条件，判断用户是否已点赞
            QueryWrapper<ArticleLikes> query = new QueryWrapper<>();
            query.eq("article_id", articleId).eq("user_id", userId);
            ArticleLikes likeRecord = articleLikeMapper.selectOne(query);

            // 查询文章记录，用于更新 likeCount
            Articles article = articlesMapper.selectById(articleId);
            if (article == null) {
                return Result.fail("文章不存在");
            }
            int affectedRows;
            if (likeRecord != null) {
                // 已点赞，执行取消点赞操作
                int deleted = articleLikeMapper.delete(query);
                if (deleted == 1) {
                    // 更新文章点赞数，如果原点赞数为 null 则视为 0
                    int likeCount = (article.getLikeCount() == null ? 0 : article.getLikeCount());
                    article.setLikeCount(likeCount > 0 ? likeCount - 1 : 0);
                    affectedRows = articlesMapper.updateById(article);
                    if (affectedRows == 1) {
                        return Result.ok("取消点赞成功");
                    } else {
                        return Result.fail("取消点赞，更新文章失败");
                    }
                } else {
                    return Result.fail("取消点赞失败");
                }
            } else {
                // 未点赞，执行点赞操作
                ArticleLikes newLike = new ArticleLikes();
                newLike.setArticleId(articleId);
                newLike.setUserId(userId);
                int inserted = articleLikeMapper.insert(newLike);
                if (inserted == 1) {
                    int likeCount = (article.getLikeCount() == null ? 0 : article.getLikeCount());
                    article.setLikeCount(likeCount + 1);
                    affectedRows = articlesMapper.updateById(article);
                    if (affectedRows == 1) {
                        return Result.ok("点赞成功");
                    } else {
                        return Result.fail("点赞，更新文章失败");
                    }
                } else {
                    return Result.fail("点赞失败");
                }
            }
        } catch (Exception e) {
            return Result.fail("操作异常：" + e.getMessage());
        }
    }


    @Transactional
    public Result<String> deleteArticle(Integer id) {
        try {
            // 删除文章
            int rows = articlesMapper.deleteById(id);
            if (rows == 0) {
                return Result.fail("删除失败，文章不存在");
            }

            // 删除文章内容
            QueryWrapper<ArticleContents> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("article_id", id);
            articleContentMapper.delete(queryWrapper);

            // 删除审核记录
            QueryWrapper<ArticleAudits> auditQuery = new QueryWrapper<>();
            auditQuery.eq("article_id", id);
            articleAuditMapper.delete(auditQuery);

            // 删除点赞记录
            QueryWrapper<ArticleLikes> likeQuery = new QueryWrapper<>();
            likeQuery.eq("article_id", id);
            articleLikeMapper.delete(likeQuery);

            // 删除浏览记录
            QueryWrapper<ArticleViews> viewQuery = new QueryWrapper<>();
            viewQuery.eq("article_id", id);
            articleViewMapper.delete(viewQuery);

            return Result.ok("删除成功");
        } catch (Exception e) {
            return Result.fail("删除失败：" + e.getMessage());
        }
    }

}
